package cn.wolfcode.luowowo.resolver;

import cn.wolfcode.luowowo.annotation.UserParam;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.service.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义参数解析器：在请求方法的参数中自动注入当前登录用户
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    //表示该参数解析器支持什么类型的参数,这里支持UserInfo类型的参数
    //如果该方法返回true，表示UserInfoArgumentResolver支持对UserInfo类型的参数进行解析
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //条件：类型为UserInfo并且带有@UserParam注解的参数才会解析
        return methodParameter.getParameterType() == UserInfo.class
                && methodParameter.hasMethodAnnotation(UserParam.class);
    }

    //执行解析逻辑，请求映射方法的形参UserInfo对象转换成当前用户的登录对象
    //上面的方法返回true，才会执行这一个方法
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {

        //请求头 —— token —— userInfo
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);//通过反射拿到请求对象
        String token = request.getHeader("token");//通过令牌拿到当前登录用户信息
        return userInfoRedisService.getUserInfoByToken(token);
    }
}
